//
//  FWAddTagViewController.m
//  BirdLoveSheep
//
//  Created by wwj on 16/4/18.
//  Copyright © 2016年 wwj. All rights reserved.
//

#import "FWAddTagViewController.h"
#import "FWTagButton.h"
#import "FWTextFild.h"
#import <SVProgressHUD.h>

@interface FWAddTagViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) UIView *contentView;
@property (weak, nonatomic) FWTextFild *textFiled;
@property (weak, nonatomic) UIButton *addTagBtn;
@property (strong, nonatomic) NSMutableArray *tagBtnArray;
@end


@implementation FWAddTagViewController

- (UIView *)contentView{
    if (_contentView == nil) {
        UIView *contentView = [[UIView alloc] init];
        contentView.x = TAGMARGIN;
        contentView.y = 64 + TAGMARGIN;
        [self.view addSubview:contentView];
        _contentView = contentView;
    }
    return _contentView;
}

- (FWTextFild *)textFiled{
    if (_textFiled == nil) {
        FWTextFild *textFiled = [[FWTextFild alloc] init];
        textFiled.x = 0;
        textFiled.y = 0;
        textFiled.height = TAGWITH;
        textFiled.font = [UIFont systemFontOfSize:15];
        textFiled.delegate = self;
        textFiled.placeholder = @"多个标签用逗号或换行分隔";
        [textFiled becomeFirstResponder];
        [textFiled addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
        
        __weak typeof (self) weakSelf = self;
        textFiled.block = ^{
            if (!weakSelf.textFiled.hasText) {
                [weakSelf onClickDelete:weakSelf.tagBtnArray.lastObject];
            }
        };
        [self.contentView addSubview:textFiled];
        _textFiled = textFiled;
    }
    return _textFiled;
}

- (UIButton *)addTagBtn{
    if (_addTagBtn == nil) {
        UIButton *addTagBtn = [[UIButton alloc] init];
        addTagBtn.hidden = YES;
        addTagBtn.height = 35;
        addTagBtn.x = 0;
        //设置文字居左
        addTagBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        addTagBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        addTagBtn.contentEdgeInsets = UIEdgeInsetsMake(0, TAGMARGIN, 0, TAGMARGIN);
        addTagBtn.backgroundColor = MyColor(97, 137, 232);
        addTagBtn.layer.cornerRadius = 4;
        [self.contentView addSubview:addTagBtn];
        _addTagBtn = addTagBtn;
    }
    return _addTagBtn;
}

- (NSMutableArray *)tagBtnArray{
    if (_tagBtnArray == nil) {
        _tagBtnArray = [NSMutableArray array];
    }
    return _tagBtnArray;
}

- (void)setTags{
    for (NSString *tag in self.tagsArray) {
        self.textFiled.text = tag;
        [self onClickAddTagBtn];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setup];
    [self contentView];
}


- (void)setup{
    self.title = @"添加标签";
    NSMutableDictionary *titDict = [NSMutableDictionary dictionary];
    titDict[NSFontAttributeName] = [UIFont systemFontOfSize:20 weight:0.2];
    [self.navigationController.navigationBar setTitleTextAttributes:titDict];
    
    NSMutableDictionary *leftDict = [NSMutableDictionary dictionary];
    leftDict[NSForegroundColorAttributeName] = [UIColor blackColor];
    leftDict[NSFontAttributeName] = [UIFont systemFontOfSize:17 weight:0.01];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(onClickCancel)];
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:leftDict forState:UIControlStateNormal];
    
    NSMutableDictionary *rightDict = [NSMutableDictionary dictionary];
    rightDict[NSForegroundColorAttributeName] = [UIColor blackColor];
    rightDict[NSFontAttributeName] = [UIFont systemFontOfSize:17 weight:0.01];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(finish)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:rightDict forState:UIControlStateNormal];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.contentView.width = self.view.width - 2 * self.contentView.x;
    self.contentView.height = self.view.height;
    
    self.textFiled.x = 0;
    self.textFiled.width = self.contentView.width;
    
    self.addTagBtn.width = self.contentView.width;
    
    [self setTags];
}


- (CGFloat)getTextFileWith{
    CGFloat textFiledWith = [self.textFiled.text sizeWithAttributes:@{NSFontAttributeName : self.textFiled.font}].width;
    return MAX(100, textFiledWith);
}

- (void)textDidChange{
    if (self.textFiled.hasText) {
        NSInteger textLenth = self.textFiled.text.length - 1;
        NSString *charStr = [self.textFiled.text substringFromIndex:textLenth];
        
        if ([charStr isEqualToString:@","] || [charStr isEqualToString:@"，"]) {
            self.textFiled.text = [self.textFiled.text substringToIndex:textLenth];
            [self onClickAddTagBtn];
        }
        self.addTagBtn.hidden = NO;
        self.addTagBtn.y = CGRectGetMaxY(self.textFiled.frame) + TAGMARGIN;
        [self.addTagBtn setTitle:[NSString stringWithFormat:@"添加标签：%@", self.textFiled.text] forState:UIControlStateNormal];
        [self.addTagBtn addTarget:self action:@selector(onClickAddTagBtn) forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        self.addTagBtn.hidden = YES;
    }
    [self updateTextFiledFrame];
}

- (void)onClickAddTagBtn{
    if (self.tagBtnArray.count == 15) {
        [SVProgressHUD showErrorWithStatus:@"最多添加15个"];
        return;
    }
    FWTagButton *tagBtn = [FWTagButton buttonWithType:UIButtonTypeCustom];
    [tagBtn setTitle:self.textFiled.text forState:UIControlStateNormal];
    [tagBtn addTarget:self action:@selector(onClickDelete:) forControlEvents:UIControlEventTouchUpInside];
    self.textFiled.text = nil;
    self.addTagBtn.hidden = YES;
    [self.contentView addSubview:tagBtn];
    [self.tagBtnArray addObject:tagBtn];
    [self updateTagBtnFrame];
    
}

- (void)onClickDelete:(FWTagButton *)tagBtn{
    [tagBtn removeFromSuperview];
    [self.tagBtnArray removeObject:tagBtn];
    [UIView animateWithDuration:0.3 animations:^{
        [self updateTagBtnFrame];
    }];
    
}

- (void)updateTagBtnFrame{
    for (NSInteger index = 0; index < self.tagBtnArray.count; index++) {
         FWTagButton *tagBtn = self.tagBtnArray[index];
        if (index == 0) {
            tagBtn.x = 0;
            tagBtn.y = 0;
        }else{
            FWTagButton *lastTagBtn = self.tagBtnArray[index - 1];
            CGFloat leftWith = CGRectGetMaxX(lastTagBtn.frame) + TAGMARGIN;
            CGFloat rightWith = self.contentView.width - leftWith;
            if (rightWith > tagBtn.width) {
                tagBtn.x = leftWith;
                tagBtn.y = lastTagBtn.y;
            }else{
                tagBtn.x = 0;
                tagBtn.y = CGRectGetMaxY(lastTagBtn.frame) + TAGMARGIN;
            }
        }
        
    }
    [self updateTextFiledFrame];
   
}

- (void)updateTextFiledFrame{
    FWTagButton *lastBtn = self.tagBtnArray.lastObject;
    CGFloat leftWith = CGRectGetMaxX(lastBtn.frame) + TAGMARGIN;
    if (self.contentView.width - leftWith > [self getTextFileWith]) {
        self.textFiled.x = leftWith;
        self.textFiled.y = lastBtn.y;
    }else{
        self.textFiled.x = 0;
        self.textFiled.y = CGRectGetMaxY(lastBtn.frame) + TAGMARGIN;
    }
    self.addTagBtn.y = CGRectGetMaxY(self.textFiled.frame) + TAGMARGIN;
}

- (void)onClickCancel{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)finish{
    if (_tagsBlock) {
        _tagsBlock([self.tagBtnArray valueForKeyPath:@"currentTitle"]);
    }
    [self onClickCancel];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.hasText) {
        [self onClickAddTagBtn];
    }
    return YES;
}

@end
